<template>
    <div class="settings-tab-container">
        <!-- 左侧按钮区域 -->
        <div class="left-sidebar">
            <div class="sidebar-header">基本设置</div>
            <div class="sidebar-section">
                <div class="section-title">网络设置</div>
                <div class="sidebar-buttons">
                    <button 
                        v-for="item in menuItems" 
                        :key="item.key"
                        class="sidebar-btn" 
                        :class="{ active: selectedComponent === item.component }"
                        @click="onMenuClick(item)"
                    >
                        <div class="btn-icon">{{ item.emoji }}</div>
                        <div class="btn-text">{{ item.title }}</div>
                    </button>
                </div>
            </div>
        </div>

        <!-- 右侧内容区域 -->
        <div class="content-area">
            <div class="content-header">{{ selectedTitle }}</div>
            <div v-loading="loading" class="content-body">
                <component :is="selectedComponent" 
                           :ref="selectedComponent === 'LocalNetworkSettings' ? 'localNetworkSettings' : 
                               selectedComponent === 'Hj212Network' ? 'hj212Network' : 
                               selectedComponent === 'OrayConfig' ? 'orayConfig' : 
                               selectedComponent === 'MqttNetworkSettings' ? 'mqttNetworkSettings' : null"
                           @settings-updated="handleSettingsUpdated"
                />
            </div>
        </div>
    </div>
</template>

<script>
import LocalNetworkSettings from '@/components/SettingTab/LocalNetworkSettings.vue'
import OrayConfig from '@/components/SettingTab/OrayConfig.vue'
import Hj212Network from '@/components/SettingTab/Hj212Network.vue'
import MqttNetworkSettings from '@/components/SettingTab/MqttNetworkSettings.vue'
import { SettingsTabManager } from '@/api/TabManager'
import { mapGetters } from 'vuex'

const menuItems = [
    {
        title: '本地网络设置',
        key: '0-0-0',
        emoji: '🖥️',
        component: 'LocalNetworkSettings'
    },
    // {
    //     title: '花生壳配置',
    //     key: '0-0-1',
    //     emoji: '☁️',
    //     component: 'OrayConfig'
    // },
    {
        title: 'HJ212网络',
        key: '0-0-2',
        emoji: '🏢',
        component: 'Hj212Network'
    },
    {
        title: 'MQTT网络',
        key: '0-0-3',
        emoji: '📡',
        component: 'MqttNetworkSettings'
    }
]

const PlaceholderComponent = {
    render(h) {
        return h('div', '此功能正在开发中...')
    }
}

export default {
    name: 'SettingsTab',
    components: {
        LocalNetworkSettings,
        OrayConfig,
        Hj212Network,
        MqttNetworkSettings,
        PlaceholderComponent
    },
    data() {
        return {
            menuItems,
            selectedTitle: '本地网络设置',
            selectedComponent: 'LocalNetworkSettings',
            settingsTabManager: new SettingsTabManager(),
            allSettingsData: null,
            loading: false,
            needsDataRefresh: false, // 标记是否需要刷新数据
            lastLoadedDeviceId: null, // 记录上次加载数据的设备ID
            forceRefreshComponents: false // 强制刷新子组件的标记
        }
    },
    computed: {
        ...mapGetters('groupTree', ['selectedDeviceId', 'selectedGroupId', 'selectedDeviceInfo', 'selectedGroupInfo'])
    },
    watch: {
        // 监听选中设备ID的变化
        selectedDeviceId: {
            handler(newDeviceId, oldDeviceId) {
                console.log('🔄 [SettingsTab] 选中设备ID变化:', { 
                    old: oldDeviceId, 
                    new: newDeviceId,
                    timestamp: new Date().toISOString(),
                    needsDataRefresh: this.needsDataRefresh,
                    lastLoadedDeviceId: this.lastLoadedDeviceId
                })
                
                // 当选中设备发生变化时
                if (newDeviceId !== oldDeviceId) {
                    if (newDeviceId) {
                        // 检查是否是真正的分组设备切换（从一个有效ID切换到另一个有效ID）
                        const isGroupDeviceSwitch = oldDeviceId && newDeviceId && oldDeviceId !== newDeviceId
                        
                        // 检查是否需要重新获取数据
                        if (this.lastLoadedDeviceId !== newDeviceId) {
                            console.log('🏷️ [SettingsTab] 设备已切换，标记需要刷新数据', {
                                isGroupDeviceSwitch,
                                reason: isGroupDeviceSwitch ? '分组设备切换' : '设备初始化'
                            })
                            this.needsDataRefresh = true
                            this.allSettingsData = null // 清空旧数据
                            
                            // 如果是分组设备切换，需要强制刷新子组件
                            if (isGroupDeviceSwitch) {
                                console.log('🔄 [SettingsTab] 检测到分组设备切换，将强制刷新子组件')
                                // 设置一个标记，用于在数据加载后强制更新子组件
                                this.forceRefreshComponents = true
                            }
                            
                            // 如果当前组件是激活状态（在SettingsTab页面），则立即加载数据
                            // 否则等待activated钩子被调用
                            if (this.isComponentActive()) {
                                console.log('🚀 [SettingsTab] 组件当前激活，立即获取设置数据...')
                                this.loadAllSettingsData()
                            } else {
                                console.log('⏳ [SettingsTab] 组件当前未激活，等待切换到SettingsTab时再获取数据')
                            }
                        }
                    } else {
                        console.log('🧹 [SettingsTab] 分组设备被清空，清除设置数据')
                        this.allSettingsData = null
                        this.needsDataRefresh = false
                        this.lastLoadedDeviceId = null
                        this.forceRefreshComponents = false
                    }
                }
            },
            immediate: true
        }
    },
    async mounted() {
        console.log('🚀 [SettingsTab] 组件 mounted，检查 Vuex 状态')
        console.log('📋 [SettingsTab] 当前选中设备ID:', this.selectedDeviceId)
        console.log('📋 [SettingsTab] 当前选中设备信息:', this.selectedDeviceInfo)
        console.log('📋 [SettingsTab] 当前选中分组ID:', this.selectedGroupId)
        console.log('📋 [SettingsTab] 当前选中分组信息:', this.selectedGroupInfo)
        console.log('📋 [SettingsTab] Vuex store 状态:', this.$store.state.groupTree)
        console.log('📋 [SettingsTab] 完整的 Vuex store:', this.$store.state)
        
        // mounted时不立即加载数据，等待用户切换到SettingsTab时才加载
        // 这样可以避免在默认的MonitorTab页面时就触发数据加载
        if (this.selectedDeviceId) {
            console.log('🏷️ [SettingsTab] mounted时发现已选中设备，标记需要刷新数据')
            this.needsDataRefresh = true
            
            // 只有当前处于SettingsTab页面时才立即加载
            if (this.isComponentActive()) {
                console.log('🔄 [SettingsTab] mounted时组件已激活，开始加载数据')
                await this.loadAllSettingsData()
            } else {
                console.log('⏳ [SettingsTab] mounted时组件未激活，等待用户切换到SettingsTab')
            }
        } else {
            console.log('⚠️ [SettingsTab] mounted时没有选中设备')
        }
    },
    async activated() {
        console.log('🚀 [SettingsTab] 组件 activated (keep-alive激活)')
        console.log('📋 [SettingsTab] activated时当前选中设备ID:', this.selectedDeviceId)
        console.log('📋 [SettingsTab] activated时需要刷新数据:', this.needsDataRefresh)
        console.log('📋 [SettingsTab] activated时上次加载的设备ID:', this.lastLoadedDeviceId)
        
        // 当组件被激活时，检查是否需要重新加载数据
        if (this.selectedDeviceId) {
            if (this.needsDataRefresh || this.lastLoadedDeviceId !== this.selectedDeviceId || !this.allSettingsData) {
                console.log('🔄 [SettingsTab] activated时需要加载数据，开始获取...')
                await this.loadAllSettingsData()
            } else {
                console.log('🔄 [SettingsTab] activated时数据已是最新，更新当前组件')
                this.$nextTick(() => {
                    this.updateCurrentComponentData()
                })
            }
        } else {
            console.log('⚠️ [SettingsTab] activated时没有选中设备')
        }
    },
    deactivated() {
        console.log('🛑 [SettingsTab] 组件 deactivated (keep-alive暂停)')
    },
    beforeDestroy() {
        console.log('🧹 [SettingsTab] 组件即将销毁')
    },
    methods: {
        onMenuClick(item) {
            this.selectedTitle = item.title
            this.selectedComponent = item.component || 'PlaceholderComponent'
            
            // 如果切换到不同的设置组件，通知子组件更新数据
            this.$nextTick(() => {
                this.updateCurrentComponentData()
            })
        },
        
        // 获取所有设置数据
        async loadAllSettingsData() {
            if (!this.selectedDeviceId) {
                console.log('⚠️ [SettingsTab] 没有选中的设备，跳过数据加载')
                return
            }
            
            this.loading = true
            try {
                console.log('🔄 [SettingsTab] 开始获取设置数据...', {
                    selectedDeviceId: this.selectedDeviceId,
                    forceRefreshComponents: this.forceRefreshComponents
                })
                this.allSettingsData = await this.settingsTabManager.getAllSettingsData()
                console.log('✅ [SettingsTab] 设置数据获取成功:', {
                    localNetworkSettings: !!this.allSettingsData.localNetworkSettings,
                    hj212NetworkSettings: !!this.allSettingsData.hj212NetworkSettings,
                    orayConfig: !!this.allSettingsData.orayConfig,
                    mqttNetworkSettings: !!this.allSettingsData.mqttNetworkSettings,
                    timestamp: this.allSettingsData.timestamp,
                    forceRefreshComponents: this.forceRefreshComponents
                })
                
                // 通知当前显示的组件更新数据
                this.$nextTick(() => {
                    this.updateCurrentComponentData()
                    // 在组件数据更新完成后再重置强制刷新标记
                    this.$nextTick(() => {
                        console.log('🔄 [SettingsTab] 组件数据更新完成，重置强制刷新标记')
                        this.forceRefreshComponents = false
                    })
                })
                
            } catch (error) {
                console.error('❌ [SettingsTab] 获取设置数据失败:', error)
                this.$message.error('获取设置数据失败: ' + (error.message || '未知错误'))
            } finally {
                this.loading = false
                this.lastLoadedDeviceId = this.selectedDeviceId // 更新记录
                this.needsDataRefresh = false // 加载完成后重置标记
                // 注意：forceRefreshComponents 现在在 $nextTick 中重置，确保组件更新完成后再重置
            }
        },
        
        // 更新当前组件的数据
        updateCurrentComponentData() {
            console.log('🔄 [SettingsTab] 更新当前组件数据', {
                hasData: !!this.allSettingsData,
                forceRefresh: this.forceRefreshComponents,
                selectedComponent: this.selectedComponent,
                timestamp: new Date().toISOString()
            })
            
            if (!this.allSettingsData) {
                console.log('⚠️ [SettingsTab] 没有设置数据，跳过更新组件')
                return
            }
            
            const currentComponent = this.getCurrentComponentRef()
            if (!currentComponent) {
                console.log('⚠️ [SettingsTab] 没有找到当前组件的引用，尝试延迟重试:', this.selectedComponent)
                // 简单的延迟重试，只重试一次
                this.$nextTick(() => {
                    const retryComponent = this.getCurrentComponentRef()
                    if (retryComponent) {
                        console.log('✅ [SettingsTab] 延迟重试成功，找到组件引用')
                        this.performComponentDataUpdate(retryComponent)
                    } else {
                        console.warn('⚠️ [SettingsTab] 延迟重试仍然无法找到组件引用')
                    }
                })
                return
            }
            
            this.performComponentDataUpdate(currentComponent)
        },
        
        // 执行组件数据更新的具体逻辑
        performComponentDataUpdate(currentComponent) {
            console.log('🔄 [SettingsTab] 更新组件数据:', {
                component: this.selectedComponent,
                hasUpdateMethod: !!currentComponent.updateData,
                forceRefresh: this.forceRefreshComponents,
                componentRef: !!currentComponent
            })
            
            // 如果需要强制刷新，先重置组件状态
            if (this.forceRefreshComponents && currentComponent.updateData) {
                console.log('🔄 [SettingsTab] 开始强制刷新子组件流程')
                console.log('🔄 [SettingsTab] 第1步：先传入null重置状态')
                // 先传入null重置组件状态
                currentComponent.updateData(null)
                // 使用nextTick确保重置操作完成后再更新数据
                this.$nextTick(() => {
                    console.log('🔄 [SettingsTab] 第2步：重置完成，开始传入新数据')
                    this.performComponentUpdate(currentComponent)
                })
            } else {
                console.log('🔄 [SettingsTab] 执行正常组件更新（非强制刷新）')
                this.performComponentUpdate(currentComponent)
            }
        },
        
        // 执行组件数据更新
        performComponentUpdate(currentComponent) {
            // 根据当前选中的组件类型，更新相应的数据
            switch (this.selectedComponent) {
                case 'LocalNetworkSettings':
                    if (this.allSettingsData.localNetworkSettings && currentComponent.updateData) {
                        console.log('📋 [SettingsTab] 更新本地网络设置:', this.allSettingsData.localNetworkSettings)
                        currentComponent.updateData(this.allSettingsData.localNetworkSettings)
                    }
                    break
                case 'Hj212Network':
                    if (this.allSettingsData.hj212NetworkSettings && currentComponent.updateData) {
                        console.log('📋 [SettingsTab] 更新HJ212网络设置:', this.allSettingsData.hj212NetworkSettings)
                        currentComponent.updateData(this.allSettingsData.hj212NetworkSettings)
                    }
                    break
                case 'OrayConfig':
                    if (this.allSettingsData.orayConfig && currentComponent.updateData) {
                        console.log('📋 [SettingsTab] 更新花生壳配置:', this.allSettingsData.orayConfig)
                        currentComponent.updateData(this.allSettingsData.orayConfig)
                    }
                    break
                case 'MqttNetworkSettings':
                    if (this.allSettingsData.mqttNetworkSettings && currentComponent.updateData) {
                        console.log('📋 [SettingsTab] 更新MQTT网络设置:', {
                            hasData: !!this.allSettingsData.mqttNetworkSettings,
                            dataCode: this.allSettingsData.mqttNetworkSettings.code,
                            dataLength: this.allSettingsData.mqttNetworkSettings.data ? this.allSettingsData.mqttNetworkSettings.data.length : 0,
                            forceRefresh: this.forceRefreshComponents,
                            componentRef: !!currentComponent,
                            updateMethod: !!currentComponent.updateData
                        })
                        currentComponent.updateData(this.allSettingsData.mqttNetworkSettings)
                    } else {
                        console.log('⚠️ [SettingsTab] MQTT网络设置数据不可用:', {
                            hasSettingsData: !!this.allSettingsData,
                            hasMqttData: !!this.allSettingsData?.mqttNetworkSettings,
                            hasComponent: !!currentComponent,
                            hasUpdateMethod: !!currentComponent?.updateData
                        })
                    }
                    break
            }
        },
        
        // 获取当前组件的引用
        getCurrentComponentRef() {
            const componentMap = {
                'LocalNetworkSettings': 'localNetworkSettings',
                'Hj212Network': 'hj212Network',
                'OrayConfig': 'orayConfig',
                'MqttNetworkSettings': 'mqttNetworkSettings'
            }
            
            const refName = componentMap[this.selectedComponent]
            console.log('🔍 [SettingsTab] 获取当前组件引用:', {
                selectedComponent: this.selectedComponent,
                refName: refName,
                hasRef: refName ? !!this.$refs[refName] : false,
                loading: this.loading
            })
            
            // 如果ref不存在但refName有效，可能是组件正在渲染中
            if (refName && !this.$refs[refName]) {
                console.log('⚠️ [SettingsTab] 组件引用暂时不可用，可能正在渲染中')
            }
            
            return refName ? this.$refs[refName] : null
        },
        
        // 获取设置数据的方法，供子组件调用
        getSettingsData(type) {
            return this.allSettingsData ? this.allSettingsData[type] : null
        },

        // 检查组件是否在 SettingsTab 页面中激活
        isComponentActive() {
            // 在keep-alive环境中，通过检查父组件的activeTab来判断当前是否在SettingsTab
            try {
                // 尝试通过$parent访问主组件的activeTab状态
                let parent = this.$parent
                while (parent) {
                    if (parent.activeTab !== undefined) {
                        const isActive = parent.activeTab === 'settings'
                        console.log('🔍 [SettingsTab] 检查激活状态:', { activeTab: parent.activeTab, isActive })
                        return isActive
                    }
                    parent = parent.$parent
                }
                console.log('⚠️ [SettingsTab] 无法检测到激活状态，假设为激活')
                return true // 如果无法检测，假设为激活状态
            } catch (error) {
                console.warn('⚠️ [SettingsTab] 检查激活状态时出错:', error)
                return true // 出错时假设为激活状态
            }
        },

        // 处理子组件设置更新事件
        handleSettingsUpdated(updatedData) {
            console.log('🔄 [SettingsTab] 收到子组件设置更新事件:', updatedData)
            
            // 确保 allSettingsData 存在
            if (!this.allSettingsData) {
                this.allSettingsData = {}
            }
            
            // 根据更新数据的类型，更新 allSettingsData
            if (updatedData.localNetworkSettings) {
                this.allSettingsData.localNetworkSettings = updatedData.localNetworkSettings
            }
            if (updatedData.hj212NetworkSettings) {
                this.allSettingsData.hj212NetworkSettings = updatedData.hj212NetworkSettings
            }
            if (updatedData.orayConfig) {
                this.allSettingsData.orayConfig = updatedData.orayConfig
            }
            if (updatedData.mqttNetworkSettings) {
                this.allSettingsData.mqttNetworkSettings = updatedData.mqttNetworkSettings
            }
            
            // 更新全局时间戳，避免重复更新
            this.allSettingsData.timestamp = new Date().getTime()
            
            console.log('✅ [SettingsTab] 所有设置数据已更新，时间戳:', this.allSettingsData.timestamp)
        }
    }
}
</script>
<style scoped>
.settings-tab-container {
    display: flex;
    height: 100%;
    background-color: #f5f5f5;
}
.left-sidebar {
    width: 200px;
    background-color: #fff;
    border-right: 1px solid #e0e0e0;
    box-shadow: 2px 0 4px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
}
.sidebar-header {
    padding: 20px 15px;
    font-size: 16px;
    font-weight: 600;
    color: #333;
    border-bottom: 1px solid #e8e8e8;
    background-color: #fafafa;
}
.sidebar-section {
    flex: 1;
    padding: 20px 0;
}
.section-title {
    padding: 0 15px 10px;
    font-size: 13px;
    color: #999;
    font-weight: 500;
}
.sidebar-buttons {
    display: flex;
    flex-direction: column;
    gap: 10px;
    padding: 0 15px;
}
.sidebar-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 15px 10px;
    border: none;
    background-color: transparent;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    width: 100%;
    text-align: center;
}
.sidebar-btn:hover {
    background-color: #f0f8ff;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.sidebar-btn.active {
    background-color: #1890ff;
    color: white;
    box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}
.btn-icon {
    font-size: 24px;
    margin-bottom: 8px;
}
.btn-text {
    font-size: 14px;
    font-weight: 500;
    line-height: 1.2;
}
.content-area {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}
.content-header {
    padding: 20px 30px;
    background-color: #fff;
    border-bottom: 1px solid #e8e8e8;
    font-size: 18px;
    font-weight: 600;
    color: #333;
}
.content-body {
    flex: 1;
    padding: 30px;
    overflow-y: auto;
    background-color: #fff;
}
</style> 